package com.zzzyh.forumsystemclient.cotroller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONException;
import com.zzzyh.forumsystemclient.common.AppResult;
import com.zzzyh.forumsystemclient.model.GetHotSearchResponse;
import com.zzzyh.forumsystemclient.model.HotSearchResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/")
public class HotSearchController {
    private final String baseUrl = "https://api.guiguiya.com/api/hotlist?type=";

    @Autowired
    private StringRedisTemplate redisTemplate;
    @RequestMapping("/getHotSearch/{type}")
    public AppResult<HotSearchResponse> getHotSearch(@PathVariable String type) {
        // 定义缓存键
        String cacheKey = "hotsearch:type:" + type;

        // 1. 检查缓存中是否已有数据
        String cachedResponseStr = redisTemplate.opsForValue().get(cacheKey);
        if (cachedResponseStr != null && !cachedResponseStr.isEmpty()) {
            // 如果缓存中有数据，直接反序列化并返回
            HotSearchResponse cachedResponse = JSONObject.parseObject(cachedResponseStr, HotSearchResponse.class);
            return AppResult.success(cachedResponse);
        }

        // 2. 缓存未命中，调用 API 获取数据
        String url = baseUrl + type;
        try {
            String responseStr = sendGetRequest(url);
            System.out.println("Raw JSON Response: " + responseStr); // 添加原始响应打印

            // 添加空值检查和异常捕获
            GetHotSearchResponse parsedResponse = null;
            if (responseStr != null && !responseStr.trim().isEmpty()) {
                try {
                    // 使用 FastJSON 解析 JSON 数据
                    parsedResponse = JSONObject.parseObject(responseStr, GetHotSearchResponse.class);
                } catch (JSONException e) {
                    e.printStackTrace();
                    throw new RuntimeException("JSON解析失败: " + e.getMessage());
                }
            } else {
                throw new RuntimeException("获取到空的API响应");
            }

            List<HotSearchResponse.HotSearchItem> data = new ArrayList<>();
            int i = 0;
            HotSearchResponse hotSearchResponse = new HotSearchResponse();
            for (GetHotSearchResponse.HotSearchItem item : parsedResponse.getData()) {
                HotSearchResponse.HotSearchItem hotSearchItem = new HotSearchResponse.HotSearchItem();
                hotSearchItem.setRank(item.getIndex());
                hotSearchItem.setKeyword(item.getTitle());
                hotSearchItem.setHotValue(item.getHot());
                hotSearchItem.setUrl(item.getUrl());
                data.add(hotSearchItem);
                i++;
                if (i >= 10) {
                    break;
                }
            }
            hotSearchResponse.setData(data);
            hotSearchResponse.setCode(200);
            hotSearchResponse.setMessage("ok");

            // 3. 将新获取的数据写入 Redis 缓存，设置有效期为 30 分钟
            String responseJson = JSONObject.toJSONString(hotSearchResponse);
            redisTemplate.opsForValue().set(cacheKey, responseJson, 30, TimeUnit.MINUTES);

            return AppResult.success(hotSearchResponse);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String sendGetRequest(String urlString) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求方法为 GET
        connection.setRequestMethod("GET");

        // 获取响应码
        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        // 读取响应内容
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            response.append(line);
        }

        reader.close();

        // 关闭连接
        connection.disconnect();

        return response.toString();
    }
}
